package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 货物模块
 */
@Controller
@RequestMapping("/cargo/contractProduct")
@Slf4j
public class ContractProductController extends BaseController {

    // 注入dubbo服务接口代理对象（注意导入的包）
    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;

    /**
     * 货物列表
     */
    @RequestMapping("/list")
    public String list(String contractId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行查询购销合同的货物列表:");

        // 构造条件对象
        ContractProductExample example = new ContractProductExample();
        ContractProductExample.Criteria criteria = example.createCriteria();
        // 条件1：company_id
        //criteria.andCompanyIdEqualTo(getLoginCompanyId());
        // 条件2：contract_id
        // SELECT * FROM co_contract_product WHERE contract_id=''
        criteria.andContractIdEqualTo(contractId);
        // 根据登陆用户的企业id查询购销合同
        PageInfo<ContractProduct> pageInfo =
                contractProductService.findByPage(example, pageNum, pageSize);

        // 查询货物的厂家
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);

        // 保存
        request.setAttribute("pageInfo", pageInfo);
        request.setAttribute("factoryList", factoryList);
        // 【存储购销合同id，主要是为了后面点击保存货物要记录购销合同id。 跳转】
        request.setAttribute("contractId", contractId);
        return "cargo/product/product-list";
    }

    @Autowired
    private FileUploadUtil fileUploadUtil;
    /**
     * 添加或修改
     *  <input type="file" name="productPhoto" >
     */
    @RequestMapping("/edit")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) {
        // 设置企业信息（从登陆用户中获取）
        contractProduct.setCompanyId(getLoginCompanyId());
        contractProduct.setCompanyName(getLoginCompanyName());

        // 判断：根据id是否为空判断执行添加还是修改
        if (StringUtils.isEmpty(contractProduct.getId())) {
            /* 处理文件上传到七牛云*/
            try {
                String url = "http://"+fileUploadUtil.upload(productPhoto);
                contractProduct.setProductImage(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            contractProductService.save(contractProduct);
        } else {
            contractProductService.update(contractProduct);
        }

        return "redirect:/cargo/contractProduct/list?contractId="+contractProduct.getContractId();
    }

    /**
     * 进入修改页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        // 根据货物id查询
        ContractProduct contractProduct = contractProductService.findById(id);

        // 查询货物厂家
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);

        // 保存
        request.setAttribute("contractProduct", contractProduct);
        request.setAttribute("factoryList", factoryList);
        return "cargo/product/product-update";
    }

    /**
     * 删除
     * @param id  货物id            [用于删除]
     * @param contractId 购销合同id [用于跳转]
     * @return
     */
    @RequestMapping("/delete")
    public String delete(String id,String contractId) {
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list?contractId=" + contractId;
    }

    /**
     * 上传货物（1）在购销合同列表，点击上传货物，进入到上传货物的页面
     */
    @RequestMapping("/toImport")
    public String toImport(String contractId) {
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    /**
     * 上传货物（2）页面选择文件，点击上传
     */
    @RequestMapping("/import")
    public String importExport(String contractId,MultipartFile file) throws IOException {
        //1. 根据excel文件流，创建工作簿
        Workbook workbook = new XSSFWorkbook(file.getInputStream());

        //2. 获取工作表
        Sheet sheet = workbook.getSheetAt(0);

        //3. 获取总行数
        int rows = sheet.getPhysicalNumberOfRows();

        //4. 遍历每一行，从第二行开始
        for (int i = 1; i < rows; i++) {
            //4.0 获取每一行
            Row row = sheet.getRow(i);

            //4.1 创建货物对象
            ContractProduct cp = new ContractProduct();

            //4.2 封装货物对象
            cp.setFactoryName(row.getCell(1).getStringCellValue());
            cp.setProductNo(row.getCell(2).getStringCellValue());
            cp.setCnumber((int) row.getCell(3).getNumericCellValue());
            cp.setPackingUnit(row.getCell(4).getStringCellValue());
            cp.setLoadingRate(String.valueOf(row.getCell(5).getNumericCellValue()));
            cp.setBoxNum((int) row.getCell(6).getNumericCellValue());
            cp.setPrice(row.getCell(7).getNumericCellValue());
            cp.setProductDesc(row.getCell(8).getStringCellValue());
            cp.setProductRequest(row.getCell(9).getStringCellValue());
            // 设置购销合同id
            cp.setContractId(contractId);
            // 根据厂家名称，查询获取厂家信息
            Factory factory = factoryService.findByFactoryName(cp.getFactoryName());
            if (factory != null) {
                cp.setFactoryId(factory.getId());
            }
            // 设置企业信息
            cp.setCompanyId(getLoginCompanyId());
            cp.setCompanyName(getLoginCompanyName());

            //4.3 添加货物
            contractProductService.save(cp);
        }
        return "redirect:/cargo/contract/list";
    }
}